package com.slorgs.business.utils

import java.nio.charset.StandardCharsets
import java.security.MessageDigest

class ShaUtil {

    companion object {
        fun getSha1(str: String): String? {
            val hexDigits = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')
            return try {
                val mdTemp = MessageDigest.getInstance("SHA1")
                mdTemp.update(str.toByteArray(StandardCharsets.UTF_8))
                val md = mdTemp.digest()
                val j = md.size
                val buf = CharArray(j * 2)
                var k = 0
                for (byte0 in md) {
                    buf[k++] = hexDigits[byte0.toInt() ushr 4 and 0xf]
                    buf[k++] = hexDigits[byte0.toInt() and 0xf]
                }
                String(buf)
            } catch (e: Exception) {
                null
            }
        }

        fun verify(plaintext: String, password: String): Boolean {
            val str = getSha1(plaintext)
            return password == str
        }
    }
}